package com.yy.socket.handler;

import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.tio.core.ChannelContext;
import org.tio.core.ChannelContextFilter;
import org.tio.core.Tio;
import org.tio.core.maintain.Users;
import org.tio.utils.lock.ObjWithLock;
import org.tio.utils.lock.SetWithLock;
import com.alibaba.fastjson.JSON;
import com.yy.ant.chat.entity.Chatmessage;
import com.yy.ant.chat.service.IChatmessageService;
import com.yy.ant.chat.service.IFlockService;
import com.yy.ant.sys.entity.User;
import com.yy.model.ReceiveMessage;
import com.yy.model.SendMessage;
import com.yy.socket.Type;
import com.yy.utils.SocketMsgUtils;

/**
 * 处理群组消息
 * 
 * @author Lenovo
 *
 */
@Service
public class GroupMessageHandler implements MsgHandlerInterface {

	@Autowired
	private IChatmessageService iChatmessageService;
	@Autowired
	private IFlockService iFlockService;

	@Value("${yy.touxiang}")
	private String url;

	@Override
	public Object handler(String text, ChannelContext context) {
		// 解析消息内容
		ReceiveMessage msgData = JSON.parseObject(text, ReceiveMessage.class);
		Map<String, String> to = msgData.getTo();
		Map<String, String> mine = msgData.getMine();
		//String id = to.get("id");
		// 构建转发消息实体
		SendMessage sendMessage = new SendMessage();
		sendMessage.setUsername(mine.get("username"));
		sendMessage.setAvatar(mine.get("avatar"));
		sendMessage.setId(to.get("id"));
		sendMessage.setType("group");
		sendMessage.setContent(mine.get("content"));
		sendMessage.setFromid(null);
		sendMessage.setTimestamp(System.currentTimeMillis());
		String strJson = JSON.toJSONString(sendMessage);
		try {
			Tio.sendToGroup(context.getTioConfig(), to.get("id"),
					SocketMsgUtils.madeWsResponse(Type.GROUP_MSG_REQ, strJson), new ChannelContextFilter() {
						@Override
						public boolean filter(ChannelContext channelContext) {
							if (channelContext == context) {
								return false;
							} else {
								return true;
							}
						}
					});
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// 存储消息,包含离线消息哦

			Chatmessage cm = new Chatmessage();
			cm.setUsername(mine.get("username"));
			cm.setAvatar(mine.get("avatar"));
			cm.setContent(mine.get("content"));
			cm.setFroms(Long.valueOf(mine.get("id")));
			cm.setTimestamp(System.currentTimeMillis());
			cm.setToid(Long.valueOf(to.get("id")));
			cm.setType(2); // 2为群组消息
			cm.setUnreadpoint(1); // 0.已读,1.未读 cm.setUsername(mine.get("username"));
			String unreadNumbers = "";
			Users users1 = context.getTioConfig().users;
			ObjWithLock<Map<String, SetWithLock<ChannelContext>>> map = users1.getMap();
			Map<String, SetWithLock<ChannelContext>> obj = map.getObj();
			String groupId = String.valueOf(to.get("id"));
			List<User> users = iFlockService.getMember(groupId, url);
			Set<String> keys = obj.keySet();
			for (int i = 0; i < users.size(); i++) {// 过滤在线用户
				if (keys.contains(String.valueOf(users.get(i).getId()))) {
					users.remove(i);
				}
			}
			for (User u : users) {// 设置未在线的人
				unreadNumbers += u.getId() + ",";
			}
			if (unreadNumbers.length() > 0) {
				unreadNumbers = unreadNumbers.substring(0, unreadNumbers.length() - 1);
			}
			cm.setUnreadnumbers(unreadNumbers);
			//System.out.println("unreadNumbers:" + unreadNumbers);
			iChatmessageService.save(cm);
		}
		return null;
	}

}
